const db = wx.cloud.database();
const _ = db.command;
const $ = db.command.aggregate;

// miniprogram/pages/note/test.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userList : [],
    conditionUserList : [],
    aggregatedUserList : []
  },
  
  //Test for-loop user basic info
  queryAllUserInfo() {
    db.collection('noteUser').get({
      success: res => {
        this.setData({
          userList: res.data
        });
        console.log('[数据库] queryAllUserInfo [查询记录] 成功: ', res);
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] queryAllUserInfo [查询记录] 失败：', err);
      }
    });
  },
  
  //Test for query specified user info
  querySpecifiedUserInfo() {
    // 查询特定用户
    db.collection('noteUser').where({
      "nickName" : "yaoyao"
    })
    .get({
      success: res => {
        this.setData({
          conditionUserList: res.data
        });
        console.log('[数据库] querySpecifiedUserInfo [查询记录] 成功: ', res);
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] querySpecifiedUserInfo [查询记录] 失败：', err);
      }
    });
  },

  //Test for aggregated user info
  queryAggregatedUserInfo() {
    /*
    Call Cloud Function due to the bug : 
    Error: errCode: -502003 database permission denied | errMsg: Permission denied
    */
    wx.cloud.callFunction({
      name : "queryAggregatedUserInfo"
    })
    .then(res => {
      let resutlList = res.result.list;

      resutlList.forEach(function(item) {
        console.log("============结果是 ：" + item.nickName + ", " + item.identityID + ", " + item.userID);
      });
      
      this.setData({
        aggregatedUserList : resutlList
      })
    })
  },

  //Test for aggregated user info by lookup
  learnAggregatedDataByLookUp() {

    /*
      Call Cloud Function due to the bug : 
      Error: errCode: -502003 database permission denied | errMsg: Permission denied
    */
    let queryRequest = {
      originCollection : "User",
      fromCollectionsLookUpParmas : [
                                 {
                                  name : "Article",
                                  params : {
                                    userID : '$userID'
                                  },
                                  pipeline : {
                                    fieldName : '$userID',
                                    definedName : '$$userID'
                                  },
                                  project : {
                                    _id: 0,
                                    articleID: 1,
                                    content: 1,
                                  },
                                  match : {
                                    fieldName : 'userID',
                                    value : 1
                                  },
                                  as : 'User2Article',
                                 },
                                 {
                                  name : "UserIdentity",
                                  params : {
                                    identityID : '$identityID',
                                  },
                                  pipeline : {
                                    fieldName : '$identityID',
                                    definedName : '$$identityID'
                                  },
                                  project : {
                                    _id: 0,
                                    identityID: 1,
                                    userIdentityDesc: 1,
                                    permissionsDesc: 1,
                                  },
                                  match : {
                                    fieldName : 'identity',
                                    value : 1
                                  },
                                  as : 'User2UserIdentity',
                                 },
      ],
    }
    //let queryRequestJSONStr = JSON.stringify(queryRequest);

    wx.cloud.callFunction({
      name : "learnAggregatedOperation",
      data : {
        queryRequest,
        //queryRequestJSONStr : wx.cloud.CDN(queryRequestJSONStr)
      }
    })
    .then(res => {
      console.log("==========返回结果原始数据：" + res.result.list);
    })
  },
  
  testFunctions() {
    //Test for aggregated user info
    //this.queryAggregatedUserInfo();

    //Test for query all user info
    //this.queryAllUserInfo();

    //Test for query specified user info
    //this.querySpecifiedUserInfo();

    //Test for aggregated user info by lookup
    //this.learnAggregatedDataByLookUp();
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //Test for learning functions
    //this.testFunctions();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})